package cn.bugstack.domain.trade.service.lock;

import cn.bugstack.domain.trade.adapter.repository.ITradeRepository;
import cn.bugstack.domain.trade.model.aggregate.GroupByOrderAggregate;
import cn.bugstack.domain.trade.model.entity.*;
import cn.bugstack.domain.trade.model.valobj.GroupBuyProgressVO;
import cn.bugstack.domain.trade.service.ITradeLockOrderService;
import cn.bugstack.domain.trade.service.lock.factory.TradeLockRuleFilterFactory;
import cn.bugstack.types.design.framework.link.model2.chain.BusinessLinkedList;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author: 小新
 * @Date: 2025/7/22 22:26
 * @Description:
 * @Version: v1.0
 */
@Service
public class TradeLockOrderService implements ITradeLockOrderService {

    @Resource
    private ITradeRepository tradeRepository;
    @Resource
    private BusinessLinkedList<TradeRuleLockCommandEntity, TradeLockRuleFilterFactory.DynamicContext, TradeLockRuleFilterBackEntity> tradeRuleFilter;// 交易规则过滤
    @Override
    public MarketPayOrderEntity queryNoPayMarketPayOrderByOutTradeNo(String userId, String outTradeNo) {
        // 查询未支付的订单
        return tradeRepository.queryNoPayMarketPayOrderByOutTradeNo(userId, outTradeNo);
    }

    @Override
    public GroupBuyProgressVO queryGroupBuyProgress(String teamId) {
        // 查询团购进度
        return tradeRepository.queryGroupBuyProgress(teamId);
    }

    @Override
    public MarketPayOrderEntity lockMarketPayOrder(UserEntity userEntity, PayDiscountEntity payDiscountEntity, PayActivityEntity payActivityEntity) throws Exception {

        // 先通过交易规则过滤
        TradeLockRuleFilterBackEntity tradeRuleFilterBackEntity = tradeRuleFilter.apply(TradeRuleLockCommandEntity.builder()
                .activityId(payActivityEntity.getActivityId())
                .userId(userEntity.getUserId())
                .teamId(payActivityEntity.getTeamId())
                .build(), new TradeLockRuleFilterFactory.DynamicContext());

        Integer userTackOrderCount = tradeRuleFilterBackEntity.getUserTackOrderCount();


        GroupByOrderAggregate groupByOrderAggregate = GroupByOrderAggregate.builder()
                .payActivityEntity(payActivityEntity)
                .payDiscountEntity(payDiscountEntity)
                .userEntity(userEntity)
                .validTime(payActivityEntity.getValidTime())
                .userTackOrderCount(userTackOrderCount)
                .build();
        try {
            return tradeRepository.lockMarkPayOrder(groupByOrderAggregate);
        }catch (Exception e){
            tradeRepository.recoveryTeamStock(tradeRuleFilterBackEntity.getTeamSocketRecoveryKey(),payActivityEntity.getValidTime());
            throw new Exception("锁定订单失败");
        }

    }
}
